import sys
from PyQt5 import QtGui, QtWidgets, QtCore
from ui import Qt_ui
import samplerate
import base64
# import tensorflow as tf
import soundfile as sf
from scipy import signal
import matplotlib.pyplot as plt
import cv2
import numpy as np
from PIL import Image
import os
import random
import time
import paho.mqtt.client as mqtt
import struct
import json

client_id = f"picture|securemode=2,signmethod=hmacsha1,timestamp=1719976922248|"
timestamp = str(int(time.time()))
username = f"picture&k17qfYOFMoU"
password = f"AF550D71D6D827463B6C1E9C06A52BA1C2715477"

broker = f"k17qfYOFMoU.iot-as-mqtt.cn-shanghai.aliyuncs.com"
port = 1883
# topic = f"/sys/k17qfYOFMoU/picture/thing/event/property/post"
topic = f"/k17qfYOFMoU/picture/user/update"
image_path = "./hs_img.jpg"

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe(f"/sys/k17qfYOFMoU/picture/thing/event/property/post")
    #注意把自己的设备信息更换
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

def band_pass_filter(original_signal, order, fc1, fc2, fs):
    b, a = signal.butter(
        N=order, Wn=[2 * fc1 / fs, 2 * fc2 / fs], btype='bandpass')
    new_signal = signal.lfilter(b, a, original_signal)
    return new_signal

def plot_signal(audio_data, title=None):
    plt.figure(figsize=(6, 4), dpi=200)
    plt.plot(audio_data, linewidth=1)
    plt.grid()
    plt.savefig('hs_data/hs_img.jpg')

class QtMain(Qt_ui):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.client = mqtt.Client(client_id=client_id)
        self.client.username_pw_set(username, password)
        self.client.on_connect = on_connect
        self.client.on_message = on_message
        self.client.connect(broker, port, 60)
        self.client.loop_start()
        self.flag = 0

    def mqtt_publish(self,da):
        random_number = random.randint(10, 500)
        payload = {
            "method": "thing.event.property.post",
            "params": {
                "image": str(random_number),
                "index": str(da)
            }
        }
        self.client.publish(topic, json.dumps(payload))
        print(f"Published: {json.dumps(payload)}")
        print(str(da))
    def mqtt_image(self):
        print("发送图片")
        da = "正常"
        self.mqtt_publish(da)
    def get_image_base64_block(self,image_path, block_size=102400):
        with open(image_path, "rb") as image_file:  #二进制
            image_data = base64.b64encode(image_file.read()).decode('utf-8')
        for i in range(0, len(image_data), block_size):
            yield image_data[i:i + block_size]

    # 发送 Base64 图像块的函数
    def publish_image_block(self,image_chunk, chunk_index):
        topic = f"/k17qfYOFMoU/picture/user/update"
        payload = {
            "method": "thing.event.property.post",
            "params": {
                "image": image_chunk,
                "chunk_index": chunk_index
            }
        }
        result = self.client.publish(topic, json.dumps(payload))
        print(f"Publishing chunk {chunk_index}: {json.dumps(payload)} with result: {result}")

    def publish_images_from_directory(self,directory):
        # while True:  # 无限循环
        #     image_files = [f for f in os.listdir(directory) if
        #                    os.path.isfile(os.path.join(directory, f)) and f.lower().endswith(('.png', '.jpg', '.jpeg'))]
        #     for image_file in image_files:
        #         image_path = os.path.join(directory, image_file)
            chunk_index = 0
            for image_chunk in self.get_image_base64_block(image_path):
                self.publish_image_block(image_chunk, chunk_index)
                chunk_index += 1
                time.sleep(1)  # 可以根据需要调整发送间隔时间
            time.sleep(2)  # 每秒发送一张图片

    def Exit(self):
        print("Exit")
        sys.exit(app.exec_())

if __name__ == "__main__":
    # QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QtWidgets.QApplication(sys.argv)
    window = QtMain()
    window.show()
    #window.showFullScreen()
    sys.exit(app.exec_())
